angular.module('BaseServer')

.factory('usbPort', ['$rootScope', '$timeout', function ($rootScope, $timeout) {
    var o = {},
        _notify = 0,
        _inputCache = '',
        _timeOut;

    // 开始监听U口输入    
    o.start = function () {
        _notify++;
        _inputCache = '';
        if (_notify > 1) {
            return;
        }
        angular.element(document).keypress(onKeyPress);
    };
    // 停止监听U口输入
    o.stop = function () {
        _notify--;
        _inputCache = '';
        if (_notify > 0) {
            return;
        }
        angular.element(document).off('keypress', onKeyPress);
    };

    return o;

    function onKeyPress (event) {
        if (_timeOut) {
            $timeout.cancel(_timeOut);
        }
        if (event.keyCode === 13) {
            if (_inputCache.length > 0) {
                $rootScope.$broadcast('usbPort.input', _inputCache);
                _inputCache = '';
            }
            return;
        }
        _inputCache += String.fromCharCode(event.keyCode);
        // 两次读入间隔小于50ms认为是U口输入，否则为人工输入，清空输入缓存
        _timeOut = $timeout(function () {
            _inputCache = '';
        }, 50);
    }
}]);